<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { login as loginAPI } from '@/api'

const router = useRouter()
const authStore = useAuthStore()

// 角色选择：'student'、'teacher' 或 'admin'
const userRole = ref('student')

// 表单数据
const formData = ref({
  account: '',
  password: '',
})

// 表单验证错误
const errors = ref({
  account: '',
  password: '',
})

// 加载状态
const loading = ref(false)

// 登录错误提示
const loginError = ref('')

// 角色配置
const roles = [
  {
    value: 'student',
    label: '学生',
    icon: '👨‍🎓',
    description: '学生登录入口',
    color: '#ff6900',
  },
  {
    value: 'teacher',
    label: '老师',
    icon: '👨‍🏫',
    description: '教师登录入口',
    color: '#ff6900',
  },
  {
    value: 'admin',
    label: '管理员',
    icon: '👨‍💼',
    description: '管理员登录入口',
    color: '#ff6900',
  },
]

// 切换角色
const switchRole = (role) => {
  userRole.value = role
  // 切换角色时清空表单和错误
  formData.value = { account: '', password: '' }
  errors.value = { account: '', password: '' }
}

// 获取当前角色信息
const currentRole = computed(() => {
  return roles.find((r) => r.value === userRole.value) || roles[0]
})

// 表单验证
const validateForm = () => {
  let isValid = true
  errors.value = { account: '', password: '' }

  // 验证账号
  if (!formData.value.account.trim()) {
    errors.value.account = '请输入账号'
    isValid = false
  } else if (formData.value.account.trim().length < 3) {
    errors.value.account = '账号长度不能少于3位'
    isValid = false
  }

  // 验证密码
  if (!formData.value.password) {
    errors.value.password = '请输入密码'
    isValid = false
  } else if (formData.value.password.length < 6) {
    errors.value.password = '密码长度不能少于6位'
    isValid = false
  }

  return isValid
}

// 登录处理
const handleLogin = async (e) => {
  e.preventDefault()

  if (!validateForm()) {
    return
  }

  loading.value = true
  loginError.value = ''

  try {
    // 调用登录 API
    const response = await loginAPI({
      username: formData.value.account,
      password: formData.value.password,
    })

    // 检查响应
    if (response.code === 0 && response.data) {
      const { token, role, user } = response.data

      // 如果前端选择的角色与后端返回的角色不一致，则视为无权限
      if (role !== userRole.value) {
        // 更友好的提示信息，针对不同选择可以定制
        if (userRole.value === 'teacher') {
          loginError.value = '当前账号没有教师权限，请使用教师账号登录'
        } else if (userRole.value === 'admin') {
          loginError.value = '当前账号没有管理员权限，请使用管理员账号登录'
        } else if (userRole.value === 'student') {
          loginError.value = '当前账号没有学生权限，请使用学生账号登录'
        } else {
          loginError.value = '当前账号无权限，请使用正确身份登录'
        }
        loading.value = false
        return
      }

      // 保存登录状态到 store
      authStore.login({ token, role, user })

      // 根据角色跳转
      if (role === 'student') {
        router.push('/student/leave/list')
      } else if (role === 'teacher') {
        router.push('/teacher/approvals')
      } else if (role === 'admin') {
        router.push('/admin/leave/list')
      } else {
        loginError.value = '未知的用户角色'
      }
    } else {
      loginError.value = response.message || '登录失败'
    }
  } catch (error) {
    console.error('登录失败:', error)
    loginError.value = error.message || '登录失败，请检查网络连接'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login-page">
    <!-- 左侧展示区 -->
    <div class="left-section">
      <div class="content-wrapper">
        <!-- Logo和标题 -->
        <div class="brand-section">
          <div class="logo">
            <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path
                d="M12 2L2 7L12 12L22 7L12 2Z"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M2 17L12 22L22 17"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M2 12L12 17L22 12"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </div>
          <h1 class="main-title">学生管理系统</h1>
          <p class="subtitle">Student Management System</p>
        </div>

        <!-- 角色展示卡片 -->
        <div class="role-cards">
          <div
            v-for="role in roles"
            :key="role.value"
            class="role-card"
            :class="{ active: userRole === role.value }"
            @click="switchRole(role.value)"
          >
            <div class="role-card-icon" :style="{ color: role.color }">
              {{ role.icon }}
            </div>
            <div class="role-card-content">
              <h3 class="role-card-title">{{ role.label }}</h3>
              <p class="role-card-desc">{{ role.description }}</p>
            </div>
            <div v-if="userRole === role.value" class="role-card-indicator">
              <svg viewBox="0 0 24 24" fill="none">
                <path
                  d="M20 6L9 17L4 12"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                />
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 背景装饰 -->
      <div class="bg-decoration"></div>
    </div>

    <!-- 右侧登录区 -->
    <div class="right-section">
      <div class="login-wrapper">
        <!-- 登录表单卡片 -->
        <div class="login-card">
          <!-- 当前角色标识 -->
          <div class="role-badge" :style="{ background: currentRole.color }">
            <span class="role-badge-icon">{{ currentRole.icon }}</span>
            <span class="role-badge-text">{{ currentRole.label }}登录</span>
          </div>

          <!-- 表单标题 -->
          <h2 class="form-title">欢迎回来</h2>
          <p class="form-subtitle">请使用{{ currentRole.label }}账号登录系统</p>

          <!-- 登录表单 -->
          <form class="login-form" @submit.prevent="handleLogin">
            <!-- 账号输入 -->
            <div class="form-group">
              <label class="form-label">账号</label>
              <div class="input-wrapper">
                <input
                  v-model="formData.account"
                  type="text"
                  class="form-input"
                  :class="{ error: errors.account }"
                  placeholder="请输入账号"
                  :disabled="loading"
                  autocomplete="username"
                />
              </div>
              <span v-if="errors.account" class="error-message">{{ errors.account }}</span>
            </div>

            <!-- 密码输入 -->
            <div class="form-group">
              <label class="form-label">密码</label>
              <div class="input-wrapper">
                <input
                  v-model="formData.password"
                  type="password"
                  class="form-input"
                  :class="{ error: errors.password }"
                  placeholder="请输入密码"
                  :disabled="loading"
                  autocomplete="current-password"
                />
              </div>
              <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
            </div>

            <!-- 登录错误提示 -->
            <div v-if="loginError" class="login-error">
              <span>{{ loginError }}</span>
            </div>

            <!-- 登录按钮 -->
            <button
              type="submit"
              class="login-btn"
              :disabled="loading"
              :style="{ background: currentRole.color }"
            >
              <span v-if="!loading">立即登录</span>
              <span v-else class="loading">
                <span class="spinner"></span>
                登录中...
              </span>
            </button>
          </form>

          <!-- 底部提示 -->
          <div class="form-footer">
            <p>选择左侧身份后，使用对应的账号密码登录</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
/* 全局样式重置 - 确保登录页面不溢出 */
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

#app {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.login-page {
  width: 100vw;
  height: 100vh;
  max-width: 100vw;
  max-height: 100vh;
  display: flex;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  box-sizing: border-box;
}
</style>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 左侧展示区 */
.left-section {
  flex: 1;
  min-width: 0;
  background: #f5f5f5;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px;
  overflow: hidden;
  box-sizing: border-box;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 30%, rgba(255, 105, 0, 0.05) 0%, transparent 50%),
    radial-gradient(circle at 80% 70%, rgba(255, 105, 0, 0.05) 0%, transparent 50%);
}

.content-wrapper {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 600px;
  max-height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
}

.brand-section {
  text-align: center;
  margin-bottom: 60px;
}

.logo {
  width: 80px;
  height: 80px;
  margin: 0 auto 24px;
  color: #ff6900;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo svg {
  width: 100%;
  height: 100%;
}

.main-title {
  font-size: 48px;
  font-weight: 700;
  color: #333333;
  margin-bottom: 12px;
  letter-spacing: -1px;
}

.subtitle {
  font-size: 18px;
  color: #666666;
  font-weight: 400;
  letter-spacing: 1px;
}

.role-cards {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.role-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 24px;
  background: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.role-card:hover {
  background: #fafafa;
  transform: translateX(8px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.role-card.active {
  background: #fff5f0;
  border-color: #ff6900;
  box-shadow: 0 4px 16px rgba(255, 105, 0, 0.15);
}

.role-card-icon {
  font-size: 40px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff5f0;
  border-radius: 12px;
  flex-shrink: 0;
}

.role-card.active .role-card-icon {
  background: #ff6900;
}

.role-card-content {
  flex: 1;
}

.role-card-title {
  font-size: 20px;
  font-weight: 600;
  color: #333333;
  margin-bottom: 4px;
}

.role-card.active .role-card-title {
  color: #ff6900;
}

.role-card-desc {
  font-size: 14px;
  color: #666666;
}

.role-card-indicator {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ff6900;
  border-radius: 50%;
  color: #ffffff;
  flex-shrink: 0;
}

.role-card-indicator svg {
  width: 18px;
  height: 18px;
}

/* 右侧登录区 */
.right-section {
  width: 480px;
  min-width: 480px;
  max-width: 480px;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  box-shadow: -2px 0 16px rgba(0, 0, 0, 0.06);
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
}

.login-wrapper {
  width: 100%;
  max-width: 400px;
  max-height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
}

.login-card {
  width: 100%;
}

.role-badge {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border-radius: 20px;
  color: #ffffff;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 32px;
}

.role-badge-icon {
  font-size: 18px;
}

.form-title {
  font-size: 32px;
  font-weight: 700;
  color: #1d1d1f;
  margin-bottom: 8px;
  letter-spacing: -0.5px;
}

.form-subtitle {
  font-size: 15px;
  color: #86868b;
  margin-bottom: 40px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
}

.input-wrapper {
  position: relative;
}

.form-input {
  width: 100%;
  padding: 14px 16px;
  font-size: 16px;
  color: #1d1d1f;
  background: #f5f5f7;
  border: 1px solid transparent;
  border-radius: 12px;
  outline: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-family: inherit;
}

.form-input::placeholder {
  color: #86868b;
}

.form-input:focus {
  background: #ffffff;
  border-color: #ff6900;
  box-shadow: 0 0 0 4px rgba(255, 105, 0, 0.1);
}

.form-input.error {
  border-color: #ff3b30;
  background: rgba(255, 59, 48, 0.05);
}

.form-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.error-message {
  font-size: 12px;
  color: #ff3b30;
  padding-left: 4px;
}

.login-btn {
  width: 100%;
  padding: 16px;
  margin-top: 8px;
  font-size: 17px;
  font-weight: 600;
  color: #ffffff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 8px rgba(255, 105, 0, 0.3);
  font-family: inherit;
}

.login-btn:hover:not(:disabled) {
  background: #ff7700 !important;
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(255, 105, 0, 0.4);
}

.login-btn:active:not(:disabled) {
  transform: translateY(0);
}

.login-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top-color: #ffffff;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.form-footer {
  margin-top: 32px;
  text-align: center;
}

.form-footer p {
  font-size: 12px;
  color: #86868b;
  line-height: 1.5;
}

.login-error {
  padding: 12px 16px;
  background: rgba(255, 59, 48, 0.1);
  border: 1px solid rgba(255, 59, 48, 0.3);
  border-radius: 8px;
  color: #ff3b30;
  font-size: 14px;
  text-align: center;
}
</style>
